package cn.rjzjh.tapestry.busi.service.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.collections.CollectionUtils;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import cn.rjzjh.tapestry.busi.SpringInit;
import cn.rjzjh.tapestry.busi.model.ca.CaRole;
import cn.rjzjh.tapestry.busi.model.ca.CaStaff;
import cn.rjzjh.tapestry.busi.service.IStaffService;
import cn.rjzjh.tapestry.tams.services.base.IHbService;

@Service("UserDetailService")
public class UserDetailService implements UserDetailsService {
	@Autowired
	private IStaffService staffService;

	@Autowired
	@Inject
	private IHbService hbService;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();

		CaStaff queryObj = new CaStaff();
		queryObj.setUserName(username);
		List<CaStaff> staffs = staffService.findValidStaff(queryObj);
		CaStaff staff = null;// 登陆的用户
		if (CollectionUtils.isNotEmpty(staffs)) {
			staff = staffs.get(0);
		}
		if (staff == null) {
			return null;
		}
		List<CaRole> roles = staffService.findRolesByStaff(staff.getId());// CollectionFactory.newList();
																			// //
																			// hbService.getQuery("from CaRole").list();//TODO
																			// 测试用
		boolean isDev = false;
		int devrole=Integer.parseInt(SpringInit.conf.getProperty("role.dev")) ;
		for (CaRole role : roles) {
			SimpleGrantedAuthority grantedAuthorityImpl = new SimpleGrantedAuthority(
					String.valueOf(role.getId()));
			auths.add(grantedAuthorityImpl);
			if (role.getId() == devrole) {
				isDev = true;
			}
		}
		UserInfo user = new UserInfo(staff, auths);
		user.setDev(isDev);
		user.getRoles().addAll(roles);
		return user;
	}

}
